package com.dwxt.cdms.service;

import com.alibaba.fastjson.JSON;
import com.dwxt.cdms.admin.service.HistoryServiceAdmin;
import com.dwxt.cdms.admin.service.UserServiceAdmin;
import com.dwxt.cdms.api.common.utils.StringUtil;
import com.dwxt.cdms.applets.service.HistoryService;
import com.dwxt.cdms.base.OperateCategory;
import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.dao.*;
import com.dwxt.cdms.entity.*;
import com.dwxt.cdms.entity.dto.CustomerDTO;
import com.dwxt.cdms.entity.vo.CustomerVO;
import com.dwxt.cdms.exception.CustomException;
import com.dwxt.cdms.util.BirthDayUtil;
import com.dwxt.cdms.util.PageUtil;
import com.dwxt.cdms.util.RedisUtil;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.common.util.PartyUtil;
import com.dwxt.common.util.SmsUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class CustomerService {

    private final CustomerMapper customerMapper;
    private final EquipmentCustomService equipmentCustomService;
    private final WatchService watchService;
    private final AiAoLeDataService aiAoLeDataService;
    private final HeartVoiceService heartVoiceService;
    private final RelationService relationService;
    private final HistoryServiceAdmin historyServiceAdmin;
    private final CommunityMapper communityMapper;
    private final UserServiceAdmin userServiceAdmin;
    private final StationMapper stationMapper;
    private final StationService stationService;
    private final SetmealService setmealService;
    private final RoleMapper roleMapper;
    private final HealthWarnRecordMapper healthWarnRecordMapper;
    private final TaskMessageMapper taskMessageMapper;
    private final CallServiceService CallServiceService;
    private final EquipmentService equipmentService;
    private final WxBindMapper wxBindMapper;
    @Autowired
    private  HistoryService historyService;
    private final DataSourceTransactionManager transactionManager;

    @Transactional
    public BaseResult insertOrUpdate(Customer customer) {
        int i = 0;
        if (customer.getDisabilityCategoryArray() != null) {
            customer.setDisabilityCategory(StringUtils.join(customer.getDisabilityCategoryArray(), ","));
        }
        if (customer.getTheOldTypeArray() != null) {
            customer.setTheOldType(StringUtils.join(customer.getTheOldTypeArray(), ","));
        }
        AdminUser user = userServiceAdmin.selectUserById(Integer.valueOf(PartyUtil.getCurrentUserId()));
        if (StringUtils.isNotBlank(user.getStationId())) {
            Integer stationId = Integer.valueOf(user.getStationId().split(",")[0]);
            customer.setStationId(stationId);
            customer.setStation(stationMapper.selectByPrimaryKey(stationId).getName());
        }
        if (customer.getSetmealIds() != null) {
            customer.setSetmeal(StringUtils.join(customer.getSetmealIds(), ","));
        } else {
            customer.setSetmeal("");
        }
        //判断是否建档操作，记录时间
        if (customer.getTransform()) {
            customer.setFilingTime(new Date());
        }
        if ("1".equals(customer.getIsSync())) {
            addContactRelation(customer);
        }

        if (StringUtil.isBlank(customer.getSignImage())) {
            customer.setSign("否");
        }

        if (customer.getId() != null) {
            i = customerMapper.updateByPrimaryKeySelective(customer);
            historyServiceAdmin.generate("修改用户：" + customer.getId(), OperateCategory.UPDATE);
        } else {
            try {
                i = customerMapper.insertSelective(customer);
                historyServiceAdmin.generate("新增用户", OperateCategory.INSERT);
            } catch (DuplicateKeyException exception) {
                return BaseResult.build(StatusCode.INFO_IS_EXIST);
            }
        }
        if (i == 1) {
            return BaseResult.ok(customer);
        } else {
            return BaseResult.build(StatusCode.FAIL);
        }
    }

    /*
     * @Author liuhongfei
     * @Description 批量删除
     * @Date 15:47 2020/9/10
     * @Param
     * @return
     */
    public BaseResult deleteByIds(Integer[] ids) {
        String currentUserId = PartyUtil.getCurrentUserId();
        List<Role> roles = roleMapper.selectByUserId(Integer.valueOf(currentUserId));
        List<Integer> collect = roles.stream().map(role -> role.getId()).collect(Collectors.toList());
        boolean b = collect.contains(1) || collect.contains(9);
        if (!b) {
            return BaseResult.build(StatusCode.NO_PERMISSION);
        }
        if (null == ids || ids.length == 0) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        int result = customerMapper.deleteCustomerByIds(ids);
        if (result > 0) {
            /** 删除了客户数据,相关联的健康数据都要删除*/
            //对应发放设备删除
            equipmentCustomService.deleteDataByCustomerIds(ids);
            //腕表
            watchService.deleteWatchDataByCustomerIds(ids);
            //爱奥乐(血压血糖)
            aiAoLeDataService.deleteAiAoLeDataByCustomerIds(ids);
            //心之声--物理删除
            heartVoiceService.deleteByCustomerIds(ids);
            historyServiceAdmin.generate("删除用户：" + Arrays.toString(ids), OperateCategory.DELETE);
            //删除关联关系
            relationService.deleteByCutomerIds(ids);
            return BaseResult.ok();
        } else {
            return BaseResult.build(StatusCode.FAIL);
        }
    }

    public Customer selectCustomerById(Integer id) {
        Customer customer = customerMapper.selectByPrimaryKey(id);
      /*  //到期时间
        if (customer.getBuyTime() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(customer.getBuyTime());
            cal.add(Calendar.YEAR, 1);
            Integer days = (int) ((cal.getTime().getTime() - new Date().getTime()) / (1000 * 3600 * 24));
            customer.setExpirationTime(days + "天");
        }
        //产品套餐
        if (StringUtils.isNotBlank(customer.getSetmeal())) {
            List<String> list = Arrays.asList(customer.getSetmeal().split(","));
            customer.setSetmeal(setmealService.selectSetmealStr(list));
        }
        if (customer.getHealthManager() != null) {
            customer.setResponsibleHealthManager(userServiceAdmin.selectUserById(customer.getHealthManager()).getUsername());
        }
        if (StringUtils.isNotBlank(customer.getSetmeal())) {
            customer.setSetmealIds(Arrays.asList(customer.getSetmeal().split(",")));
        }*/
        return dealResult(customer);
    }

    public BaseResult selectByQuery(Integer pageNum, Integer pageSize, Customer customer, Integer minAge, Integer maxAge,
                                    Date startTime, Date endTime, Integer expirationDays, Boolean isFiled) {
        /*CustomerExample customerExample = new CustomerExample();
        CustomerExample.Criteria criteria = customerExample.createCriteria();
        customerExample.setOrderByClause("fileNumber is null,LEFT(fileNumber,2)!='ws', fileNumber");*/
        Integer stationId;
        try {

            stationId = stationService.getLoginUserStation();
        } catch (NumberFormatException e) {
            return BaseResult.build(StatusCode.NO_STATION);
        }
        if (stationId != null) {
            customer.setStationId(stationId);
        }
        customer.setMaxAge(maxAge);
        customer.setMinAge(minAge);
        PageHelper.startPage(pageNum, pageSize);
        Map map = JSON.parseObject(JSON.toJSONString(customer), Map.class);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("expirationDays", expirationDays);
        map.put("isFiled", isFiled);
        List<Customer> customers = customerMapper.selectCustomerList(map);
        for (Customer customer1 : customers) {
            //到期时间
            if (customer1.getBuyTime() != null) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(customer1.getBuyTime());
                cal.add(Calendar.YEAR, 1);
                Integer days = (int) ((cal.getTime().getTime() - new Date().getTime()) / (1000 * 3600 * 24));
                customer1.setExpirationTime(days + "天");
            }
            //产品套餐
            if (StringUtils.isNotBlank(customer1.getSetmeal())) {
                List<String> list = Arrays.asList(customer1.getSetmeal().split(","));
                customer1.setSetmeal(setmealService.selectSetmealStr(list));
            }
            if (StringUtils.isNotBlank(customer1.getDisabilityCategory())) {
                customer1.setDisabilityCategoryArray(customer1.getDisabilityCategory().split(","));
            }
            if (StringUtils.isNotBlank(customer1.getTheOldType())) {
                customer1.setTheOldTypeArray(customer1.getTheOldType().split(","));
            }
            if (StringUtils.isNotBlank(customer1.getIdNumber())) {
                customer1.setAge(BirthDayUtil.getAgeByIDNumber(customer1.getIdNumber()));
            }
            Optional.ofNullable(customer1.getCommunity_id()).map(id -> communityMapper.selectByPrimaryKey(id))
                    .ifPresent(community -> {
                        customer1.setCommunity(community.getName());
                    });
        }
        return BaseResult.ok(new PageInfo(customers));
    }

    public BaseResult insertAndSelectCustomerInfo(String phone) {
        CustomerExample example = new CustomerExample();
        example.createCriteria().andPhoneEqualTo(phone);
        List<Customer> customers = customerMapper.selectByExample(example);
        Boolean isCommunityManager = false;
        Boolean isEmployee = false;
        AdminUser user = userServiceAdmin.selectByPhone(phone);
        if (user != null) {
            List<Role> roles = roleMapper.selectByUserId(user.getId());
            if (roles != null && roles.size() > 0) {
                isCommunityManager = roles.stream().anyMatch(role -> role.getId().equals(13));
                if (user.getStationId().split(",").length == 1) {
                    isEmployee = roles.stream().anyMatch(role -> role.getId().equals(14));
                }
            }
        }
        if (customers.size() > 0) {
            //Customer customer = customers.get(0);
            Customer cus = customers.get(0);
            Map<String, Object> map = customerMapper.selectCountByCustomerId(cus.getId()).get(0);
            Customer customer = relationService.selectDefaultRelationCustomer(cus.getId());
            Optional.ofNullable(cus.getIdNumber()).ifPresent(idNumber -> {
                cus.setAge(BirthDayUtil.getAgeByIDNumber(idNumber));
            });
            map.put("me", cus);
            map.put("default", customer);
            map.put("isCommunityManager", isCommunityManager);
            map.put("isEmployee", isEmployee);
            return BaseResult.ok(map);
        } else {
            Customer customer = new Customer();
            customer.setPhone(phone);
            customer.setType(2);
            customer.setRegisterType(2);
            customerMapper.insertSelective(customer);
            Map map = new HashMap();
            map.put("me", customer);
            map.put("isCommunityManager", isCommunityManager);
            map.put("isEmployee", isEmployee);
            map.put("default", null);
            map.put("equipmentCount", 0);
            map.put("relationCount", 0);
            map.put("partCount", 0);
            sendRegisterMessage(customer.getId());
            return BaseResult.ok(map);
        }
    }

    public void sendRegisterMessage(Integer id) {
        try {
            TaskMessageExample example = new TaskMessageExample();
            TaskMessageExample.Criteria criteria = example.createCriteria();
            criteria.andTypeEqualTo("2");
            List<TaskMessage> messageList = taskMessageMapper.selectByExample(example);
            for (TaskMessage taskMessage : messageList) {
                HealthMessage msg = new HealthMessage();
                msg.setType(taskMessage.getTitle());
                msg.setContent(taskMessage.getContent());
                msg.setCustomerId(id);
                msg.setId(UUID.randomUUID().toString());
                healthWarnRecordMapper.insertMessage(msg);
                taskMessage.setCount(taskMessage.getCount() + 1);
                taskMessage.setStatus("1");
                taskMessage.setSendTime(new Date());
                taskMessageMapper.updateByPrimaryKeySelective(taskMessage);
            }
        } catch (Exception e) {
            log.error("注册消息发送失败！异常为：" + e.toString());
        }
    }

    public BaseResult selectWatchCustomer(Page page, Customer customer) {
        customer.setStationId(stationService.getLoginUserStation());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<Customer> customers = customerMapper.selectWatchCustomer(customer);
        return BaseResult.ok(new PageInfo(customers));

    }

    public List<Customer> selectOverThreeMonth() {
        CustomerExample example = new CustomerExample();
        example.createCriteria().andCreate_timeLessThan(new Date(System.currentTimeMillis() - (long) 90 * 24 * 60 * 60 * 1000)).andTypeNotEqualTo(2);
        return customerMapper.selectByExample(example);
    }

    public List<Customer> selectByManagerPhone(String phone) {
        CustomerExample example = new CustomerExample();
        example.createCriteria().andManagerPhoneEqualTo(phone);
        return customerMapper.selectByExample(example);
    }

    public Customer selectOrInsert(String phone) {
        CustomerExample example = new CustomerExample();
        example.createCriteria().andPhoneEqualTo(phone);
        List<Customer> customers = customerMapper.selectByExample(example);
        if (customers.size() > 0) {
            return customers.get(0);
        } else {
            Customer customer = new Customer();
            customer.setPhone(phone);
            customer.setType(3);
            customer.setRegisterType(3);
            customerMapper.insertSelective(customer);
            return customer;
        }

    }

    public BaseResult sendMessage(Integer id, String phone) {
        Customer customer = customerMapper.selectByPrimaryKey(id);
        if (phone == null) {
            if (customer != null && StringUtils.isNotBlank(customer.getManagerPhone())) {
                phone = customer.getManagerPhone();
            } else {
                Customer first = relationService.selectPhoneNotNullFirst(id);
                if (first != null) {
                    phone = first.getPhone();
                } else {
                    return BaseResult.build(StatusCode.PHONE_NOT_EXIST);
                }
            }
        }
        String message = customer.getName() + "老人未按照标准佩戴健康手环，特此通知并希望子女协调老人配合";
        sendMessage(phone, message);
        return BaseResult.ok();
    }

    private void sendMessage(String phone, String message) {
        try {
            String postData =
                    "account=ZTCQ888&password=ZTCQ888&mobile=" + phone + "&content=" + java.net.URLEncoder.encode(message,
                            "utf-8");
            SmsUtil.SMS(postData);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    public BaseResult addManagerPhone(Integer id, String phone) {
        Customer customer = customerMapper.selectByPrimaryKey(id);
        customer.setManagerPhone(phone);
        customerMapper.updateByPrimaryKeySelective(customer);
        Customer manager = selectOrInsert(phone);
        try {
            relationService.insertDefault(customer.getId(), manager.getId());
        } catch (DuplicateKeyException e) {
            //return BaseResult.build(StatusCode.ALREADY_RELATION);
        }
        return BaseResult.ok();
    }

    public List<Customer> selectIdNumberNotNull() {
        CustomerExample example = new CustomerExample();
        example.createCriteria().andIdNumberIsNotNull();
        return customerMapper.selectByExample(example);
    }

    public BaseResult selectCommunityCustomerList(Integer pageNum, Integer pageSize, String nameOrPhone, String phone) {
        AdminUser user = userServiceAdmin.selectByPhone(phone);
        Customer customer = new Customer();
        if (StringUtils.isNotBlank(nameOrPhone)) {
            customer.setPhone(nameOrPhone);
            customer.setName(nameOrPhone);
        }
        if (user != null) {
            Customer loginCustomer = customerMapper.selectByPhone(phone);
            List<Role> roles = roleMapper.selectByUserId(user.getId());
            if (roles != null && roles.size() > 0) {
                if (roles.stream().anyMatch(role -> role.getId().equals(13))) {//社区管理
                    customer.setCommunityManager(user.getId());
                } else if (roles.stream().anyMatch(role -> role.getId().equals(9))) {//区域管理
                    customer.setStationId(loginCustomer.getStationId());
                    customer.setCommunity_id(null);
                } else if (roles.stream().anyMatch(role -> role.getId().equals(1))) {//超级管理
                    customer.setCommunity_id(null);
                    customer.setStationId(null);
                } else {
                    return BaseResult.build(StatusCode.PERMISSION_FAIL);
                }

            }
        } else {
            return BaseResult.build(StatusCode.PERMISSION_FAIL);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Customer> customers = customerMapper.selectCommunityCustomerList(customer);
        customers = customers.stream().map(customer1 -> {
            //产品套餐
            if (StringUtils.isNotBlank(customer1.getSetmeal())) {
                List<String> list = Arrays.asList(customer1.getSetmeal().split(","));
                customer1.setSetmeal(setmealService.selectSetmealStr(list));
            }
            //到期时间
            if (customer1.getBuyTime() != null) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(customer1.getBuyTime());
                cal.add(Calendar.YEAR, 1);
                Integer days = (int) ((cal.getTime().getTime() - new Date().getTime()) / (1000 * 3600 * 24));
                customer1.setExpirationTime(days + "天");
            }
            return customer1;
        }).collect(Collectors.toList());
        return BaseResult.ok(new PageInfo(customers));
    }

    public BaseResult selectCustomerInfoById(Integer customerId) {
        Customer cus = customerMapper.selectByPrimaryKey(customerId);
        if (cus == null) {
            return BaseResult.build(StatusCode.NO_CUSTOMER);
        }
        Boolean isCommunityManager = false;
        AdminUser user = userServiceAdmin.selectByPhone(cus.getPhone());
        if (user != null) {
            List<Role> roles = roleMapper.selectByUserId(user.getId());
            if (roles != null && roles.size() > 0) {
                isCommunityManager = roles.stream().anyMatch(role -> role.getId().equals(13));
            }
        }
        Map<String, Object> map = customerMapper.selectCountByCustomerId(cus.getId()).get(0);
        Customer customer = relationService.selectDefaultRelationCustomer(cus.getId());
        Optional.ofNullable(cus.getIdNumber()).ifPresent(idNumber -> {
            cus.setAge(BirthDayUtil.getAgeByIDNumber(idNumber));
        });
        map.put("me", cus);
        map.put("default", customer);
        map.put("isCommunityManager", isCommunityManager);
        return BaseResult.ok(map);
    }

    public Customer selectCustomerByPhone(String phone) throws ParseException {
        Customer customer = customerMapper.selectByPhone(phone);
        BaseResult baseResult = historyService.index2(customer.getId());
        customer.setHealthData(baseResult.getData());
        return dealResult(customer);

    }

    public Customer dealResult(Customer customer) {
        //到期时间
        if (customer.getBuyTime() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(customer.getBuyTime());
            cal.add(Calendar.YEAR, 1);
            Integer days = (int) ((cal.getTime().getTime() - new Date().getTime()) / (1000 * 3600 * 24));
            customer.setExpirationTime(days + "天");
        }
        //产品套餐
        if (StringUtils.isNotBlank(customer.getSetmeal())) {
            List<String> list = Arrays.asList(customer.getSetmeal().split(","));
            customer.setSetmeal(setmealService.selectSetmealStr(list));
            customer.setSetmealIds(list);
        }
        if (customer.getHealthManager() != null) {
            customer.setResponsibleHealthManager(userServiceAdmin.selectUserById(customer.getHealthManager()).getUsername());
        }
        if (StringUtils.isNotBlank(customer.getDisabilityCategory())) {
            customer.setDisabilityCategoryArray(customer.getDisabilityCategory().split(","));
        }
        if (StringUtils.isNotBlank(customer.getTheOldType())) {
            customer.setTheOldTypeArray(customer.getTheOldType().split(","));
        }
        return customer;
    }

    @Transactional
    public BaseResult UpdateForWx(Customer customer) {
        int i = 0;
        if (customer.getDisabilityCategoryArray() != null) {
            customer.setDisabilityCategory(StringUtils.join(customer.getDisabilityCategoryArray(), ","));
        }
        if (customer.getTheOldTypeArray() != null) {
            customer.setTheOldType(StringUtils.join(customer.getTheOldTypeArray(), ","));
        }
        if (customer.getId() != null) {
            i = customerMapper.updateByPrimaryKeySelective(customer);
        } else {
            try {
                i = customerMapper.insertSelective(customer);
            } catch (DuplicateKeyException exception) {
                return BaseResult.build(StatusCode.INFO_IS_EXIST);
            }
        }
        if (i == 1) {
            return BaseResult.ok(customer);
        } else {
            return BaseResult.build(StatusCode.FAIL);
        }
    }

    public List<Map> selectCustomerRelationPeople(Integer customerId) {
        List<CallService> list = CallServiceService.list();
        List<Map> collect = list.stream().map(contact -> JsonUtils.jsonToPojo(JsonUtils.objectToJson(contact), Map.class)).collect(Collectors.toList());
        List<Map> list1 = customerMapper.selectCustomerRelationPeople(customerId);
        collect.addAll(list1);
        return collect;
    }

    public List<Map> selectCustomerIndexRelationPeople(Integer customerId) {
        return customerMapper.selectCustomerIndexRelationPeople(customerId);
    }

    public BaseResult selectAllCustomerList(String phone, Integer type) {
        CustomerExample customerExample = new CustomerExample();
        customerExample.createCriteria().andPhoneLike("%" + phone + "%").andTypeEqualTo(type);
        List<Customer> customers = customerMapper.selectByExample(customerExample);
        for (Customer customer : customers) {
            dealResult(customer);
        }
        return BaseResult.ok(customers);
    }

    @Transactional(rollbackFor = Exception.class)
    public BaseResult employeeAddCustomer(CustomerDTO dto) {
        //1.获取事务定义
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        //2.设置事务隔离级别，开启新事务
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        //3.获得事务状态
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            //查询营业员的区域
            AdminUser adminUser = userServiceAdmin.selectByPhone(dto.getCustomerPhone());
            //判断是不是营业员
            List<Role> roles = roleMapper.selectByUserId(adminUser.getId());
            if (roles != null && roles.size() > 0) {
                boolean b = roles.stream().anyMatch(role -> role.getId().equals(14));
                if (!b) {
                    return BaseResult.build(StatusCode.PERMISSION_FAIL);
                }
            }
            //判断营业员的区域是否唯一
            if (StringUtils.isBlank(adminUser.getStationId()) || adminUser.getStationId().split(",").length > 1) {
                return BaseResult.build(StatusCode.EMPLOYEE_STATION_ERROR);
            }
            //查询用户是否存在
            Customer oldCustomer = customerMapper.selectByPhone(dto.getPhone());
            if (oldCustomer != null) {
                return BaseResult.build(StatusCode.PHONE_EXIST);
            }
            Customer customer = new Customer();
            BeanUtils.copyProperties(dto, customer);
            customer.setStationId(Integer.valueOf(adminUser.getStationId()));
            customer.setStation(adminUser.getStation());
            customer.setFilingTime(new Date());
            customer.setArchivist(adminUser.getUsername() + "+" + adminUser.getPhone());
            int i = customerMapper.insertSelective(customer);
            if (i != 1) {
                return BaseResult.build(StatusCode.ADD_CUSTOMER_ERROR);
            }
            historyServiceAdmin.generateLog(dto.getCustomerPhone(), "营业员新建客户" + customer.getPhone(), OperateCategory.INSERT);
            if (StringUtils.isNotBlank(dto.getRelationPhone())) {
                //查询关联人是否存在,不存在则新增
                Customer relationCustomer = customerMapper.selectByPhone(dto.getRelationPhone());
                if (relationCustomer == null) {
                    relationCustomer = new Customer();
                    relationCustomer.setName(dto.getRelationName());
                    relationCustomer.setPhone(dto.getRelationPhone());
                    relationCustomer.setStationId(Integer.valueOf(adminUser.getStationId()));
                    relationCustomer.setStation(adminUser.getStation());
                    int i1 = customerMapper.insertSelective(relationCustomer);
                    if (i1 > 0) {
                        historyServiceAdmin.generateLog(dto.getCustomerPhone(), "营业员新建客户关联人" + relationCustomer.getPhone(), OperateCategory.INSERT);
                    }
                }
                //添加关联关系
                Relation relation = new Relation();
                relation.setCustomerId(relationCustomer.getId());
                relation.setRelateId(customer.getId());
                relationService.insert(relation);
            }
            //添加设备
            List<Equipment> equipmentList = dto.getEquipmentList();
            if (equipmentList != null && equipmentList.size() > 0) {
                for (Equipment equipment : equipmentList) {
                    Equipment equip = equipmentService.selectEquipmentBySerialNumber(equipment.getSerialNumber());
                    //判断系统内是否有当前设备
                    if (equip != null) {
                        EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(equip.getSerialNumber());
                        if (equipmentCustom != null) {
                            return BaseResult.build(StatusCode.YES_BIND_EQUIPMENT);
                        } else {
                            //绑定
                            EquipmentCustom ec = new EquipmentCustom();
                            ec.setCustomerId(customer.getId());
                            ec.setEquipmentId(equip.getId());
                            int i1 = equipmentCustomService.bindEquipment(ec);
                            historyServiceAdmin.generateLog(dto.getCustomerPhone(), "营业员绑定设备" + equip.getSerialNumber(), OperateCategory.INSERT);
                        }
                    } else {//不存在则新建设备并绑定
                        equipment.setIsEnabled("1");
                        equipment.setName(dto.getName());
                        equipment.setStationId(Integer.valueOf(adminUser.getStationId()));
                        equipment.setStation(adminUser.getStation());
                        Equipment orUpdateEquipment = equipmentService.createOrUpdateEquipment(equipment);
                        //绑定
                        EquipmentCustom ec = new EquipmentCustom();
                        ec.setCustomerId(customer.getId());
                        ec.setEquipmentId(equipment.getId());
                        int i1 = equipmentCustomService.bindEquipment(ec);
                        historyServiceAdmin.generateLog(dto.getCustomerPhone(), "营业员添加绑定设备" + orUpdateEquipment.getSerialNumber(), OperateCategory.INSERT);
                    }
                }
            }
            transactionManager.commit(status);
            return BaseResult.ok(customer);
        } catch (Exception e) {
            e.printStackTrace();
            transactionManager.commit(status);
            return BaseResult.build(StatusCode.ADD_CUSTOMER_ERROR);
        }
    }

    public BaseResult privacy(Integer customerId, String sign) {
        int i = customerMapper.privacy(customerId, sign);
        return BaseResult.ok(i);
    }

    public BaseResult insertCustomerZT(Customer customer) {
        Customer customer1 = customerMapper.selectByPhone(customer.getPhone());
        if (customer1 != null) {
            return BaseResult.build(StatusCode.PHONE_EXIST);
        }
        customer.setType(2);
        customer.setWiredUser("是");
        customer.setWiredUsername(customer.getName());
        customer.setWiredUserphone(customer.getPhone());
        return BaseResult.ok(customerMapper.insertSelective(customer));
    }

    public boolean isWxBind(Integer customerId) {
        WxBind wxBind = new WxBind();
        wxBind.setCustomerId(customerId);
        wxBind.setStatus(1);
        List<WxBind> list = wxBindMapper.select(wxBind);
        if (list != null && list.size() > 0) {
            return true;
        }
        return false;
    }

    public List<Customer> selectCustomerList() {
        CustomerExample customerExample = new CustomerExample();
        customerExample.createCriteria().andIsDeleteEqualTo(0).andTypeEqualTo(1);
        return customerMapper.selectByExample(customerExample);
    }

    /**
     * @Description:同步紧急联系人到关联人
     * @Param [customer]
     * @Return void
     * @Author chendq
     * @Date 2022/2/18
     **/
    private void addContactRelation(Customer customer) {
        if (StringUtil.isNotBlank(customer.getContactPhone())) {
            addRelation(customer.getId(), customer.getContactPhone(), customer.getContactName());
        }
        if (StringUtil.isNotBlank(customer.getContactPhone1())) {
            addRelation(customer.getId(), customer.getContactPhone1(), customer.getContactName1());
        }
        if (StringUtil.isNotBlank(customer.getContactPhone2())) {
            addRelation(customer.getId(), customer.getContactPhone2(), customer.getContactName2());
        }
    }

    private void addRelation(Integer relateId, String phone, String name) {
        Customer customer1 = customerMapper.selectByPhone(phone);
        Relation relation = new Relation();
        if (customer1 != null) {
            relation.setCustomerId(customer1.getId());
        } else {
            // 该手机如果未注册就新建用户
            Customer customer = new Customer();
            customer.setPhone(phone);
            if (StringUtil.isNotBlank(name)) {
                customer.setName(name);
            }
            int i = customerMapper.insertSelective(customer);
            relation.setCustomerId(customer.getId());
        }
        relation.setRelateId(relateId);
        relationService.insert(relation);
    }


    public void save72HourNoDataCustomerToRedis() {
        List<CustomerVO> list = customerMapper.select72HourNoDataCustomer();
        RedisUtil.set("72HourNoDataCustomerList", list);
    }

    public BaseResult select72HourNoDataCustomerList(Page page) {
        List list = RedisUtil.get("72HourNoDataCustomerList", List.class);
        if (list != null) {
            List pageList = PageUtil.getPage(list, page.getPageNum(), page.getPageSize());
            PageInfo<Object> pageInfo = new PageInfo<>(pageList);
            pageInfo.setTotal(list.size());
            pageInfo.setPageNum(page.getPageNum());
            pageInfo.setPageSize(page.getPageSize());
            return BaseResult.ok(pageInfo);
        }
        return BaseResult.ok();
    }

    public BaseResult updateSign(Integer customerId, String signImage) {
        String sign = "是";
        Date signTime = new Date();
        int i = customerMapper.updateSign(customerId,signImage,signTime,sign);
        return BaseResult.ok(customerMapper.selectByPrimaryKey(customerId));
    }
}
